import { fundPriceReq, etfPriceReq, stockPriceReq, bondPriceReq } from '@/api/stock'
import type { ReqFun, InnerData, FundData } from '@/api/stock'
import { useHistory } from './useHistory'
const { handleHistory } = useHistory()
import type { HoldType } from './model'
import type { HoldItem } from '@/indexDB/initHold'
import { ref } from 'vue'

export const typeReqMap: Record<HoldType, ReqFun> = {
  'fund-out': fundPriceReq,
  'convertibleBonds': bondPriceReq,
  'fund-in': etfPriceReq,
  'stock': stockPriceReq,
  'currency': () => Promise.reject('不支持货币类型')
}

const getInnerData = (res: InnerData) => {
  const { C, D, S } = res
  return {
    riseAndFall: C.value,
    price: D.value as number,
    latestTime: S.value as string
  }
}

const getFundData = (res: FundData) => {
  const { A, B, D } = res
  return {
    riseAndFall: D.value,
    price: B.value as number,
    latestTime: A.value as string
  }
}

export const useLatestPrice = (activeHold: HoldItem, handleEditHoldItem: (form: HoldItem) => void) => {
  const { type, code, holdNum, latestPrice, holdPrice } = activeHold
  const nowPrice = ref(latestPrice)
  if (code && type && holdNum) {
    // 未填写code，或持仓数量为0，跳过
    const req = typeReqMap[type]
    req([code]).then((res) => {
      if (res) {
        let resData
        if (type === 'fund-out') {
          resData = getFundData(res as FundData)
        } else {
          resData = getInnerData(res as InnerData)
        }
        const { price, latestTime, riseAndFall } = resData
        nowPrice.value = price
        const nowValue = +(holdNum * price).toFixed(4)
        const nowEarning = +((price - holdPrice) * holdNum).toFixed(4)
        const nowEarningPercent = ((price - holdPrice) / holdPrice * 100).toFixed(2) + '%'
        const nowHoldItem: HoldItem = {
          ...activeHold,
          latestPrice: price,
          holdValue: nowValue,
          priceTime: new Date(latestTime).getTime() + '',
          holdEarnings: nowEarning,
          holdEarningsPercent: nowEarningPercent,
          riseAndFall: riseAndFall + '%'
        }
        handleHistory(nowHoldItem)
        handleEditHoldItem(nowHoldItem)

      }
    })
  }
  return nowPrice.value
}